#pragma once
#include <iostream>
#include<vector>
#include<pthread.h>
#include<semaphore.h>
template<class T>
class RingQueue
{
    static const int defaultNum=20;
private:
    //--
    void P(sem_t& sem)
    {
        //wait
        sem_wait(&sem);
    }
    //++
    void V(sem_t&sem)
    {
        //post
        sem_post(&sem);
    }

    void Lock(pthread_mutex_t& mtx)
    {
        pthread_mutex_lock(&mtx);
    }
    void Unlock(pthread_mutex_t&mtx)
    {
        pthread_mutex_unlock(&mtx);
    }
public:
    RingQueue(int maxCapacity=defaultNum)
        :_ringQueue(maxCapacity),_maxCapacity(maxCapacity),c_step(0),p_step(0)
    {
        sem_init(&cdata_sem,0,0);
        sem_init(&pspace_sem,0,maxCapacity);
        pthread_mutex_init(&c_mtx,nullptr);
        pthread_mutex_init(&p_mtx,nullptr);
    }

    void Push(const T&in) //生产
    {   
        P(pspace_sem);
        Lock(p_mtx);
        _ringQueue[p_step]=in;
        p_step++;
        p_step%=_maxCapacity;
        Unlock(p_mtx);
        // std::cout<<"Push Unlock?"<<std::endl;
        V(cdata_sem);
    }
    void Pop(T*out) //消费
    {
        P(cdata_sem);
        Lock(c_mtx);
        *out=_ringQueue[c_step];
        c_step++;
        c_step%=_maxCapacity;

        Unlock(c_mtx);
        V(pspace_sem);
    }
    ~RingQueue()
    {
        sem_destroy(&cdata_sem);
        sem_destroy(&pspace_sem);

        pthread_mutex_destroy(&c_mtx);
        pthread_mutex_destroy(&p_mtx);
    }
private:
    std::vector<T> _ringQueue;
    int _maxCapacity;
    //生产者与消费者下标
    int c_step;
    int p_step;
    //消费者关注的数据资源
    sem_t cdata_sem;
    //生产者关注的空间资源
    sem_t pspace_sem;

    //锁
    pthread_mutex_t c_mtx;
    pthread_mutex_t p_mtx;

};